package com.geping.etl.common.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.geping.etl.common.entity.*;
import com.geping.etl.common.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



/**
 * 角色分配
 * @author Administrator
 *
 */
@RestController
public class RoleDistributionController {
	
	@Autowired
	private Sys_OrgService sys_OrgService;
	@Autowired
	private Sys_UserAndOrgDepartmentService sys_UserAndOrgDepartmentService;
	@Autowired
	private Sys_Auth_RoleService sys_Auth_RoleService;
    @Autowired
    private Sys_Auth_Role_UserService sys_Auth_Role_UserService;
    @Autowired
    private RoleDistributionService roleDistributionService;
    @Autowired
	private Sys_SubjectService sss;
	
	@RequestMapping(value="/role_distribution",method=RequestMethod.GET)
	public ModelAndView roleDistribution(){
		ModelAndView model = new ModelAndView();
		List<Sys_Org> orgList = sys_OrgService.findAllSysOrg();
		model.addObject("orgList",orgList);
		
		List<Sys_UserAndOrgDepartment> organduserList = sys_UserAndOrgDepartmentService.findAllSysUser();
		model.addObject("organduserList",organduserList);
		
		model.setViewName("common/role_distribution");
		return model;
	}
	
	//根据用户ID模糊查询
	@RequestMapping(value="/getUserAndOrgDepartmentByLikeLoginID",method=RequestMethod.GET)
	public ModelAndView getUserAndOrgDepartmentByLikeLoginID(HttpServletRequest request){
		ModelAndView model = new ModelAndView();
		String loginId = "";
		try {
			loginId = URLDecoder.decode(request.getParameter("loginId").replaceAll("%","%25"), "utf-8");
			if (loginId.contains("%")){
				loginId = loginId.replace("%","djskdffhdfka");
			}else if (loginId.contains("_")){
				loginId = loginId.replace("_","djskdffhdfkb");
			}
			List<Sys_UserAndOrgDepartment> organduserList = new ArrayList<>();
			if(StringUtils.isNotBlank(loginId)) {
				organduserList = sys_UserAndOrgDepartmentService.findSysUserByLoginID(loginId);
			}else {
				organduserList = sys_UserAndOrgDepartmentService.findAllSysUser();
			}

			if (loginId.contains("djskdffhdfka")){
				loginId = loginId.replace("djskdffhdfka","%");
			}else if (loginId.contains("djskdffhdfkb")){
				loginId = loginId.replace("djskdffhdfkb","_");
			}

			model.addObject("organduserList",organduserList);
			model.addObject("loginId",loginId);
			List<Sys_Org> orgList = sys_OrgService.findAllSysOrg();
			model.addObject("orgList",orgList);
			model.setViewName("common/role_distribution");
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return model;
	}
	
	@RequestMapping(value="getSysAuthRole_roleNameAndDescription",method=RequestMethod.POST)
	public void getSysAuthRole_roleNameAndDescription(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html"); 
	    response.setContentType("text/plain; charset=utf-8");
	    
	    //先判断是否已经有权限，如果有权限的话，先回显权限
	    String userId = request.getParameter("userId");
	    List<Sys_Auth_Role_User> sysAuthRoleUserList= sys_Auth_Role_UserService.findSysAuthRoleUserByRoleId(userId);
	    
	    String subjectId = request.getParameter("subjectId");
	    
	    List<Sys_Auth_Role> list = null;
	    
	    if(subjectId == null || subjectId.equals("all")) {
	    	//获取到角色名称和角色描述
		     list = sys_Auth_RoleService.getSysAuthRoleNotStop();
	    }else {
	    	 list = sys_Auth_RoleService.findRoleBySubjectId(subjectId);
	    }
        List<Sys_Subject> subjectList = sss.findAllSubject();
	    JSONObject json = new JSONObject();
		PrintWriter out;
		try {
			out = response.getWriter();
			json.put("list",list);
			json.put("sysAuthRoleUserList",sysAuthRoleUserList);
			json.put("subjectList",subjectList);
			out.print(json.toString());
			out.flush();
			out.close();
		} catch (IOException e){
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value="saveSys_Auth_Role_User",method=RequestMethod.POST)
	public void saveSys_Auth_Role_User(HttpServletRequest request,HttpServletResponse response){
		
		String jsonStr = request.getParameter("mydata");
		JSONArray array= JSONArray.fromObject(jsonStr);
		//只要点了保存按钮，不管数据库中是否有此roleId，都会执行一次删除方法。
		JSONObject jsonTwo;
		for(int i = 0;i<1;i++){
			jsonTwo = (JSONObject) array.get(i);
			String userId = jsonTwo.get("userId").toString();
						
			//Integer deleteforSysAuthRoleUser;
			//若要保存role_Id的数据到数据库时，先删除所有role_Id之前的数据
			sys_Auth_Role_UserService.deleteSysAuthRoleUser(userId);
		}
		
		JSONObject jsonOne;
		//Sys_Auth_Role_User sys_AuthRole_User = null;
		for (int i = 0; i < array.size(); i++) {
			jsonOne = (JSONObject) array.get(i);
			Sys_Auth_Role_User sys_auth_role_user = new Sys_Auth_Role_User();
			String roleId = jsonOne.get("roleId").toString();
			String userId = jsonOne.get("userId").toString();
			String biaoshi = jsonOne.get("biaoshi").toString();
			
			if (biaoshi.equals("0")) {
				sys_auth_role_user.setRoleId(roleId);
				sys_auth_role_user.setUserId(userId);
				
				sys_Auth_Role_UserService.save(sys_auth_role_user);
			}

		}
		PrintWriter out;
		try {
				out = response.getWriter();
				out.write("1");
				out.flush();
				out.close();
			
		} catch (IOException e){
			e.printStackTrace();
		}
	} 
	
	
	
	@RequestMapping(value="/findUserOrgDepartmentByOrgId",method=RequestMethod.POST)
	public void findUserOrgDepartmentByOrgId(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html"); 
	    response.setContentType("text/plain; charset=utf-8");
	    
		final String orgId = request.getParameter("orgId");
		boolean isOpenMoreOrg = request.getSession().getAttribute("user_more_org").equals("on");

		List<Sys_UserAndOrgDepartment> userOrgDepartmentList = new ArrayList<>();
		if (isOpenMoreOrg) {
			userOrgDepartmentList = roleDistributionService.findUserOrgDepartmentLikeOrgId(orgId);
		} else {
			userOrgDepartmentList = roleDistributionService.findUserOrgDepartmentByOrgId(orgId);
		}
		userOrgDepartmentList = userOrgDepartmentList.stream().distinct().collect(Collectors.toList());
		JSONObject json = new JSONObject();
		PrintWriter out;
		try {
			out = response.getWriter();
			json.put("userOrgDepartmentList",userOrgDepartmentList);
			json.put("orgId", orgId);
			out.print(json.toString());
			out.flush();
			out.close();
		} catch (IOException e){
			e.printStackTrace();
		}
	}
	
	
}
